﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using QuanLyHocPhi.BLL;
using QuanLyHocPhi.Model;
using QuanLyHocPhi.GUI.DuLieu;
namespace QuanLyHocPhi.GUI.TacNghiep
{
    public partial class QuanLyPhieuThu : FormBase
    {
        private bool isLoad = true;
        private bool isLoadHK = true;
        private bool isLoadKTS = true;
        private decimal tongTien = 0;
        public QuanLyPhieuThu()
        {
            InitializeComponent();
        }

        private void QuanLyPhieuThu_Load(object sender, EventArgs e)
        {
            if (Program.NguoiSuDung.VaiTro == 0)
            {
                //colTrangThai.Visible = false;
                colChuyen.Visible = false;
                colXoa.Visible = false;
            }
            else
            {
                //colTrangThai.Visible = true;
                colChuyen.Visible = true;
                colXoa.Visible = true;
            }
            List<long> quyenSo = null;
            IList<Truong> listTruong = null;
            IList<string> namHoc = null;
            FormProgress frm = new FormProgress();
            frm.DoWork += delegate(object oSender, DoWorkEventArgs oE)
            {
                quyenSo = BizPhieuThu.GetDanhSachQuyenSo();
                listTruong = BizTruong.GetList_Truong();
                namHoc = BizHocKy.GetList_NamHoc();
            };
            frm.RunWorkerCompleted += delegate(object oSender, RunWorkerCompletedEventArgs oE)
            {
                if (oE.Error != null)
                {
                    string msg = oE.Error.Message;
                    if (oE.Error.InnerException != null)
                        msg += oE.Error.InnerException.Message;
                    DialogUtils.ShowError(msg);
                }

            };
            frm.StartWorking(this);


            
            cmbQuyen.DataSource = quyenSo;
            //Load danh sách trường
            
            cmbTruong.DataSource = listTruong;
            cmbTruongTime.DataSource = listTruong;
            cmbTruong.DisplayMember = "TenTruong";
            cmbTruong.ValueMember = "MaTruong";
            cmbTruongTime.DisplayMember = "TenTruong";
            cmbTruongTime.ValueMember = "MaTruong";
            
            cmbNamHoc.DataSource = namHoc;
            cmbNamTime.DataSource = namHoc;
            isLoad = false;
            cmbTruong_SelectedIndexChanged(sender, e);
            cmbTruongTime_SelectedIndexChanged(sender, e);
            cmbNamHoc_SelectedIndexChanged(sender, e);
            cmbNamTime_SelectedIndexChanged(sender, e);
        }

        private void gridQuaTrinhNopHocPhi_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1)
                return;
            var maPhieuThu = gridPhieuThu.Rows[e.RowIndex].Cells[0].Value.ToString();
            var phieuThu = BizPhieuThu.GetPhieuThu(maPhieuThu);
            if (e.ColumnIndex == 10)
            {
                //Chỉnh sửa phiếu thu

                if (phieuThu != null)
                {
                    ChiTietPhieuThu frmChiTiet = new ChiTietPhieuThu(phieuThu);
                    frmChiTiet.ShowDialog();
                    bntOKLop_Click(sender, e);
                }
            }
            else if (e.ColumnIndex == 11)
            {
                //Chuyển phiếu thu cho một sinh viên khác
                SelectSinhVienDialog dl = new SelectSinhVienDialog();
                if (dl.ShowDialog() == DialogResult.OK)
                {
                    string maSinhVienMoi = dl.SelectedSinhVien.MaSinhVien;
                    FormThuHocPhiSinhVien frm = new FormThuHocPhiSinhVien(maSinhVienMoi, true);
                    frm.ShowDialog();
                    string maLopHocPhanMoi = frm.MaLopHocPhan;
                    if (!string.IsNullOrEmpty(maLopHocPhanMoi))
                    {
                        //Thực hiện chuyển phiếu thu
                        if (phieuThu != null)
                        {
                            var maSinhVienCu = phieuThu.MaSinhVien;
                            var maLopHocPhanCu = phieuThu.KC_MaLopHocPhan;
                            phieuThu.MaSinhVien = maSinhVienMoi;
                            phieuThu.KC_MaLopHocPhan = maLopHocPhanMoi;
                            BizPhieuThu.UpdatePhieuThu(phieuThu);

                            var lopHP_SVCu = BizSinhVien.GetLopHocPhan_SinhVien(maSinhVienCu, maLopHocPhanCu);
                            if (lopHP_SVCu != null)
                            {
                                lopHP_SVCu.MaPhieuThu = "";
                                BizPhieuThu.Update_LopHocPhan_SinhVienKhongChuyen(lopHP_SVCu);
                            }
                            var lopHP_SVMoi = BizSinhVien.GetLopHocPhan_SinhVien(maSinhVienMoi, maLopHocPhanMoi);
                            if (lopHP_SVMoi != null)
                            {
                                lopHP_SVMoi.MaPhieuThu = phieuThu.MaPhieuThu;
                                BizPhieuThu.Update_LopHocPhan_SinhVienKhongChuyen(lopHP_SVMoi);
                                MessageBox.Show("Đã chuyển phiếu thu thành công", "Thông báo");
                                gridPhieuThu.Rows.RemoveAt(e.RowIndex);
                            }
                        }
                    }

                }
            }
            else if (e.ColumnIndex == 12)
            {
                if (MessageBox.Show("Bạn có muốn xóa phiếu thu này không?", "Chú ý", MessageBoxButtons.OKCancel,
                                       MessageBoxIcon.Question) == DialogResult.OK)
                {
                    //Xóa phiếu thu
                    if (phieuThu != null)
                    {
                        //Lấy thông tin phiếu thu tương ứng với mã phiếu thu
                        var maSinhVien = phieuThu.MaSinhVien;
                        var maLopHocPhan = phieuThu.KC_MaLopHocPhan;
                        var lopHPSV = BizSinhVien.GetLopHocPhan_SinhVien(maSinhVien, maLopHocPhan);
                        if (lopHPSV != null)
                        {
                            //Cập nhật lại lopHocPhan_SinhVien voi MaPhieuThu = null
                            lopHPSV.MaPhieuThu = "";
                            BizPhieuThu.Update_LopHocPhan_SinhVienKhongChuyen(lopHPSV);
                        }
                        //Xóa phiếu thu này trong csdl
                        if (BizPhieuThu.Delete(phieuThu) == true)
                            MessageBox.Show("Đã xóa phiếu thu thành công", "Thông báo", MessageBoxButtons.OK,
                                            MessageBoxIcon.Information);
                        //Xóa dòng này trên grid
                        gridPhieuThu.Rows.RemoveAt(e.RowIndex);
                    }
                }
            }
        }

        private void bntOKQuyen_Click(object sender, EventArgs e)
        {
            if (cmbQuyen.SelectedIndex == -1)
                return;
            string quyen = cmbQuyen.SelectedValue.ToString();
            string soPhieu = txtSoPhieu.Text;
            int namThu = string.IsNullOrEmpty(txtNamThu.Text) ? 0 : int.Parse(txtNamThu.Text);
            FormProgress frm = new FormProgress();
            frm.DoWork += delegate(object oSender, DoWorkEventArgs oE)
            {
                var danhSachPhieuThu = BizPhieuThu.GetDanhSachPhieuThu(quyen, soPhieu, namThu);
                HienThi(danhSachPhieuThu);
            };
            frm.RunWorkerCompleted += delegate(object oSender, RunWorkerCompletedEventArgs oE)
            {
                if (oE.Error != null)
                {
                    string msg = oE.Error.Message;
                    if (oE.Error.InnerException != null)
                        msg += oE.Error.InnerException.Message;
                    DialogUtils.ShowError(msg);
                }

            };
            frm.StartWorking(this);
            bdsPhieuThu.DataSource = tbb;
            colMaSV.DataPropertyName = "MaSinhVien";
            colHo.DataPropertyName = "Ho";
            colTen.DataPropertyName = "Ten";
            colLop.DataPropertyName = "LopGoc";
            colLopHocPhan.DataPropertyName = "LopHocPhan";
            colMaPhieuThu.DataPropertyName = "MaPhieuThu";
            colQuyen.DataPropertyName = "Quyen";
            colSoPhieu.DataPropertyName = "SoPhieu";
            colSoTien.DataPropertyName = "SoTien";
            colTrangThai.DataPropertyName = "ChinhSua";
            colChuyen.DataPropertyName = "Chuyen";
            colNgayThu.DataPropertyName = "NgayThu";
            colXoa.DataPropertyName = "Xoa";
            gridPhieuThu.AllowUserToAddRows = false;
            gridPhieuThu.AllowUserToDeleteRows = false;
            gridPhieuThu.AutoGenerateColumns = false;
            gridPhieuThu.ReadOnly = true;
            gridPhieuThu.DataSource = bdsPhieuThu;

        }

        private void cmbTruong_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!isLoad)
            {
                isLoadKTS = true;
                var listKhoaTuyenSinh = BizLopGoc.GetList_KhoaTuyenSinh(cmbTruong.SelectedValue.ToString());
                cmbKhoaTS.DataSource = listKhoaTuyenSinh;
                LoadLopHP();
                isLoadKTS = false;
            }
        }

        private void cmbNamHoc_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!isLoad)
            {
                isLoadHK = true;
                cmbHocKy.DataSource = null;
                if (cmbNamHoc.SelectedIndex == -1)
                    return;
                var namHoc = cmbNamHoc.SelectedItem.ToString();
                var lstHocKy = BizHocKy.GetList_HocKy(namHoc);
                cmbHocKy.DataSource = lstHocKy;
                cmbHocKy.DisplayMember = "SoHieuHocKy";
                LoadLopHP();
                isLoadHK = false;
            }
        }

        private void cmbHocKy_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!isLoadHK)
                LoadLopHP();
        }

        private void bntOKLop_Click(object sender, EventArgs e)
        {
            if (cmbLopHocPhan.SelectedIndex == -1)
                return;
            string lopHP = cmbLopHocPhan.SelectedValue.ToString();
            tbb = null;
            bdsPhieuThu.DataSource = null;
            gridPhieuThu.AutoGenerateColumns = false;
            gridPhieuThu.DataSource = bdsPhieuThu;
            this.Refresh();
            FormProgress frm = new FormProgress();
            frm.DoWork += delegate(object oSender, DoWorkEventArgs oE)
            {
                var danhSachPhieuThu = BizPhieuThu.GetDanhSachPhieuThu(lopHP, 1);
                HienThi(danhSachPhieuThu);
            };
            frm.RunWorkerCompleted += delegate(object oSender, RunWorkerCompletedEventArgs oE)
            {
                if (oE.Error != null)
                {
                    string msg = oE.Error.Message;
                    if (oE.Error.InnerException != null)
                        msg += oE.Error.InnerException.Message;
                    DialogUtils.ShowError(msg);
                }

            };
            frm.StartWorking(this);
            bdsPhieuThu.DataSource = tbb;
            colMaSV.DataPropertyName = "MaSinhVien";
            colHo.DataPropertyName = "Ho";
            colTen.DataPropertyName = "Ten";
            colLop.DataPropertyName = "LopGoc";
            colLopHocPhan.DataPropertyName = "LopHocPhan";
            colMaPhieuThu.DataPropertyName = "MaPhieuThu";
            colQuyen.DataPropertyName = "Quyen";
            colSoPhieu.DataPropertyName = "SoPhieu";
            colSoTien.DataPropertyName = "SoTien";
            colTrangThai.DataPropertyName = "ChinhSua";
            colChuyen.DataPropertyName = "Chuyen";
            colNgayThu.DataPropertyName = "NgayThu";
            colXoa.DataPropertyName = "Xoa";
            gridPhieuThu.AllowUserToAddRows = false;
            gridPhieuThu.AllowUserToDeleteRows = false;
            gridPhieuThu.AutoGenerateColumns = false;
            gridPhieuThu.ReadOnly = true;
            gridPhieuThu.DataSource = bdsPhieuThu;

        }

        private void cmbKhoaTS_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!isLoadKTS)
                LoadLopHP();
        }

        void LoadLopHP()
        {
            cmbLopHocPhan.DataSource = null;
            if (cmbTruong.SelectedIndex == -1 || cmbKhoaTS.SelectedIndex == -1 || cmbNamHoc.SelectedIndex == -1 || cmbHocKy.SelectedIndex == -1)
                return;
            int hk = 1;
            int result = 0;
            if (int.TryParse(cmbHocKy.Text, out result))
                hk = int.Parse(cmbHocKy.Text);
            var listLopHp = BizLopHocPhan.GetListLopHocPhan(cmbTruong.SelectedValue.ToString(), int.Parse(cmbKhoaTS.SelectedItem.ToString()), cmbNamHoc.SelectedItem.ToString(), hk);
            cmbLopHocPhan.DataSource = listLopHp;
            cmbLopHocPhan.DisplayMember = "TenLopHocPhan";
            cmbLopHocPhan.ValueMember = "MaLopHocPhan";
        }

        void HienThi(List<PhieuThu> danhSachPhieuThu)
        {
            if (danhSachPhieuThu.Count > 0)
            {
                tbb = new DataTable();
                tbb.Columns.Add("MaSinhVien", typeof(string));
                tbb.Columns.Add("MaPhieuThu", typeof(string));
                tbb.Columns.Add("Ho", typeof(string));
                tbb.Columns.Add("Ten", typeof(string));
                tbb.Columns.Add("LopGoc", typeof(string));
                tbb.Columns.Add("LopHocPhan", typeof(string));
                tbb.Columns.Add("Quyen", typeof(string));
                tbb.Columns.Add("SoPhieu", typeof(string));
                tbb.Columns.Add("SoTien", typeof(string));
                tbb.Columns.Add("ChinhSua", typeof(string));
                tbb.Columns.Add("Chuyen", typeof(string));
                tbb.Columns.Add("NgayThu", typeof(string));
                tbb.Columns.Add("Xoa", typeof(string));
                foreach (var pt in danhSachPhieuThu)
                {
                    DataRow row = tbb.NewRow();

                    row["MaSinhVien"] = string.IsNullOrEmpty(pt.MaSinhVien) == true ? "" : pt.MaSinhVien;
                    row["MaPhieuThu"] = pt.MaPhieuThu;
                    if (pt.SinhVien == null)
                    {
                        pt.SinhVien = BizSinhVien.GetSinhVienByMaSinhVien(pt.MaSinhVien);
                    }
                    if (pt.SinhVien != null)
                    {
                        row["Ho"] = pt.SinhVien.HoDem;
                        row["Ten"] = pt.SinhVien.Ten;
                    }
                    row["Quyen"] = pt.QuyenSo;
                    row["SoPhieu"] = pt.SoPhieuThu;
                    row["SoTien"] = pt.SoTien.ToString().FormatCurrency();
                    row["ChinhSua"] = "Chỉnh sửa";
                    row["Xoa"] = "Xóa";
                    row["Chuyen"] = "Chuyển";
                    row["NgayThu"] = string.Format("{0:dd/MM/yyyy}", pt.NgayThu);
                    if (true)//pt.SinhVien.MaLoai == (int)LoaiSinhVien.SinhVienKhongChuyen)
                    {
                        LopHocPhan lopHocPhan = BizLopHocPhan.GetLopHocPhanByMaLHP(pt.KC_MaLopHocPhan);
                        if (lopHocPhan != null)
                            row["LopHocPhan"] = lopHocPhan.TenLopHocPhan;
                        Lop lop = BizLopGoc.GetLopByMaLop(pt.SinhVien.KC_MaLop);
                        if (lop != null)
                            row["LopGoc"] = lop.TenLop;
                    }
                    //else
                    //{
                    //    Nganh nganh = BizLopChuyenNganh.GetLopChuyenNganhByMaLCN(pt.SinhVien.C_MaLopChuyenNganh).Nganh;
                    //    if (nganh != null)
                    //        row["LopGoc"] = nganh.TenNganh;
                    //    LopHocPhanChuyenNganh lopChuyenNganh = BizLopHocPhanChuyenNganh.GetLopHocPhanChuyenNganhByMaLHPCN(pt.C_MaLopHocPhanChuyenNganh);
                    //    if (lopChuyenNganh != null)
                    //        row["LopHocPhan"] = lopChuyenNganh.TenLopHocPhanChuyenNganh;
                    //}
                    tbb.Rows.Add(row);
                }
            }
        }

        private DataTable tbb = null;
        void HienThi2(List<PhieuThu> danhSachPhieuThu)
        {
            tbb = new DataTable();
            tongTien = 0;
            if (danhSachPhieuThu.Count > 0)
            {
                tbb.Columns.Add("MaSinhVien", typeof(string));
                tbb.Columns.Add("MaPhieuThu", typeof(string));
                tbb.Columns.Add("Ho", typeof(string));
                tbb.Columns.Add("Ten", typeof(string));
                tbb.Columns.Add("LopGoc", typeof(string));
                tbb.Columns.Add("LopHocPhan", typeof(string));
                tbb.Columns.Add("Quyen", typeof(string));
                tbb.Columns.Add("SoPhieu", typeof(string));
                tbb.Columns.Add("SoTien", typeof(string));
                tbb.Columns.Add("ChinhSua", typeof(string));
                tbb.Columns.Add("Chuyen", typeof(string));
                tbb.Columns.Add("NgayThu", typeof(string));
                tbb.Columns.Add("Xoa", typeof(string));
                foreach (var pt in danhSachPhieuThu)
                {
                    if (pt.SinhVien==null)
                        pt.SinhVien = BizSinhVien.GetSinhVienByMaSinhVien(pt.MaSinhVien);
                    if (pt.SinhVien != null)
                    {
                        DataRow row = tbb.NewRow();
                        row["MaSinhVien"] = pt.MaSinhVien;
                        row["MaPhieuThu"] = pt.MaPhieuThu;
                        row["Ho"] = pt.SinhVien.HoDem;
                        row["Ten"] = pt.SinhVien.Ten;
                        row["Quyen"] = pt.QuyenSo;
                        row["SoPhieu"] = pt.SoPhieuThu;
                        row["SoTien"] = pt.SoTien.ToString().FormatCurrency();
                        tongTien += pt.SoTien;
                        row["ChinhSua"] = "Chỉnh sửa";
                        row["Xoa"] = "Xóa";
                        row["Chuyen"] = "Chuyển";
                        row["NgayThu"] = string.Format("{0:dd/MM/yyyy}", pt.NgayThu);
                        if (true)//pt.SinhVien.MaLoai == (int)LoaiSinhVien.SinhVienKhongChuyen)
                        {
                            LopHocPhan lopHocPhan = BizLopHocPhan.GetLopHocPhanByMaLHP(pt.KC_MaLopHocPhan);
                            if (lopHocPhan != null)
                                row["LopHocPhan"] = lopHocPhan.TenLopHocPhan;
                            Lop lop = BizLopGoc.GetLopByMaLop(pt.SinhVien.KC_MaLop);
                            if (lop != null)
                                row["LopGoc"] = lop.TenLop;
                        }
                        tbb.Rows.Add(row);
                    }
                    else
                        MessageBox.Show("MSV: " + pt.MaSinhVien + ", MPT: " + pt.MaPhieuThu, "Lỗi");
                }

            }
        }

        private void bntOKTime_Click(object sender, EventArgs e)
        {
            try
            {
                lbTongtien.Text = "Tổng tiền: 0 đồng";
                var maTruong = cmbTruongTime.SelectedValue.ToString();
                var namTS = int.Parse(cmbNamTSTime.SelectedItem.ToString());
                var namHoc = cmbNamTime.SelectedItem.ToString();
                var hocKy = int.Parse(cmbHKTime.Text);
                var tu = dtFrom.Value.Date;
                var den = dtTo.Value.Date;
                bdsPhieuThu.DataSource = null;
                gridPhieuThu.AutoGenerateColumns = false;
                gridPhieuThu.DataSource = bdsPhieuThu;
                this.Refresh();
                FormProgress frm = new FormProgress();
                frm.DoWork += delegate(object oSender, DoWorkEventArgs oE)
                {
                    var danhSachPhieuThu = BizPhieuThu.GetDanhSachPhieuThuTheoThoiGian(maTruong, namTS,
                                                                                       namHoc, hocKy, tu,
                                                                                       den);
                    HienThi2(danhSachPhieuThu);
                };
                frm.RunWorkerCompleted += delegate(object oSender, RunWorkerCompletedEventArgs oE)
                {
                    if (oE.Error != null)
                    {
                        string msg = oE.Error.Message;
                        if (oE.Error.InnerException != null)
                            msg += oE.Error.InnerException.Message;
                        DialogUtils.ShowError(msg);
                    }

                };
                frm.StartWorking(this);
                lbTongtien.Text = "Tổng tiền: " + tongTien.ToString().FormatCurrency() + " đồng";
                this.Refresh();
                bdsPhieuThu.DataSource = tbb;
                colMaSV.DataPropertyName = "MaSinhVien";
                colHo.DataPropertyName = "Ho";
                colTen.DataPropertyName = "Ten";
                colLop.DataPropertyName = "LopGoc";
                colLopHocPhan.DataPropertyName = "LopHocPhan";
                colMaPhieuThu.DataPropertyName = "MaPhieuThu";
                colQuyen.DataPropertyName = "Quyen";
                colSoPhieu.DataPropertyName = "SoPhieu";
                colSoTien.DataPropertyName = "SoTien";
                colTrangThai.DataPropertyName = "ChinhSua";
                colChuyen.DataPropertyName = "Chuyen";
                colNgayThu.DataPropertyName = "NgayThu";
                colXoa.DataPropertyName = "Xoa";
                gridPhieuThu.AllowUserToAddRows = false;
                gridPhieuThu.AllowUserToDeleteRows = false;
                gridPhieuThu.AutoGenerateColumns = false;
                gridPhieuThu.ReadOnly = true;
                gridPhieuThu.DataSource = bdsPhieuThu;
            }
            catch
            {
                MessageBox.Show("Lỗi. Bạn phải chọn dữ liệu trước khi nhấn nút OK", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }


        }
        //private bool isLoadKTSTime = true;
        private void cmbTruongTime_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!isLoad)
            {
                var listKhoaTuyenSinh = BizLopGoc.GetList_KhoaTuyenSinh(cmbTruongTime.SelectedValue.ToString());
                cmbNamTSTime.DataSource = listKhoaTuyenSinh;
            }
        }

        private void cmbNamTSTime_SelectedIndexChanged(object sender, EventArgs e)
        {
            //if (!isLoadKTSTime)
            //    LoadLopHP();
        }
        private bool isLoadHKTime = true;
        private void cmbNamTime_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!isLoad)
            {
                isLoadHKTime = true;
                cmbHocKy.DataSource = null;
                if (cmbNamHoc.SelectedIndex == -1)
                    return;
                var namHoc = cmbNamTime.SelectedItem.ToString();
                var lstHocKy = BizHocKy.GetList_HocKy(namHoc);
                cmbHKTime.DisplayMember = "SoHieuHocKy";
                cmbHKTime.DataSource = lstHocKy;
                cmbHocKy.DisplayMember = "SoHieuHocKy";
                cmbHocKy.DataSource = lstHocKy;
                isLoadHKTime = false;
            }
        }

        private void txtNamThu_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                bntOKQuyen_Click(sender, e);
            }
            if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "\\d+"))
            {
                e.Handled = true;
            }
        }

        private void txtSoPhieu_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                bntOKQuyen_Click(sender, e);
            }
        }

        private void cmbTruongThoiGian_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}
